package com.gyw.myapplication.xyaxis;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by yangyi on 2018/12/9.
 */

public class AxisBackgroundByDivider extends RecyclerView.ItemDecoration {
    private Drawable mDivider;
    private int mDividerHeight = 2;//分割线高度，默认为1px

    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};


    public AxisBackgroundByDivider(Context context) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }



    //获取分割线尺寸
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(0, 0, 0, mDividerHeight);
    }

    //绘制分割线
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        drawBackground(c,parent);

    }

    //绘制横向 item 分割线
    private void drawBackground(Canvas canvas, RecyclerView parent) {

        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            View child = parent.getChildAt(i);
            int hLeft=child.getLeft();
            int hRight=child.getRight();
            int hTop=child.getTop()+child.getHeight()/2;
            int hBottom=hTop+mDividerHeight;
            int vLeft=child.getLeft()+child.getWidth()/2;
            int vRight=vLeft+mDividerHeight;
            int vTop=child.getTop();
            int vBottom=child.getBottom();
            if(mDivider!=null){
                mDivider.setBounds(hLeft,hTop,hRight,hBottom);
                mDivider.draw(canvas);

                mDivider.setBounds(vLeft,vTop,vRight,vBottom);
                mDivider.draw(canvas);
            }


        }
    }

}
